// ============================================================================
//
// Copyright (C) 2006-2007 Dengues
//
// Google Group: http://groups.google.com/group/dengues
//
// QQ Group: 24885404
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//
// ============================================================================
package org.dengues.ui.cdc;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.dengues.commons.IDenguesCoreContants;
import org.dengues.commons.utils.DenguesTextUtil;
import org.dengues.core.metadata.MetadataHelper;
import org.dengues.core.resource.DenguesProjectFactory;
import org.dengues.core.resource.WarehouseResourceFactory;
import org.dengues.core.warehouse.ENodeCategoryName;
import org.dengues.core.warehouse.IWarehouseView;
import org.dengues.model.database.DBTable;
import org.dengues.model.database.DatabaseDiagram;
import org.dengues.model.database.DiagramChild;
import org.dengues.model.project.CDCConnType;
import org.dengues.model.project.ConnPropertySetType;
import org.dengues.model.project.ProjectType;
import org.dengues.ui.prefs.StructuredViewerAndButtons;
import org.dengues.ui.prefs.connectivity.models.ConnectivityCategory;
import org.dengues.ui.prefs.connectivity.models.ConnectivityProvider;
import org.eclipse.emf.common.util.EList;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.StructuredViewer;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;

/**
 * Qiang.Zhang.Adolf@gmail.com class global comment. Detailled comment <br/>
 * 
 * $Id: Dengues.epf Qiang.Zhang.Adolf@gmail.com 2008-5-4 qiang.zhang $
 * 
 */
public class CDCSettingsViewer extends StructuredViewerAndButtons {

    class CDCViewerProvider extends LabelProvider implements ITableLabelProvider, IStructuredContentProvider {

        /*
         * (non-Javadoc)
         * 
         * @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnImage(java.lang.Object, int)
         */
        public Image getColumnImage(Object element, int columnIndex) {
            return null;
        }

        /*
         * (non-Javadoc)
         * 
         * @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnText(java.lang.Object, int)
         */
        public String getColumnText(Object element, int columnIndex) {
            if (element instanceof CDCConnType) {
                CDCConnType type = (CDCConnType) element;
                ConnPropertySetType cdcConn = type.getConnSet();
                switch (columnIndex) {
                case 0:
                    return DenguesTextUtil.getNotNullString(type.getName());
                case 1:
                    ConnectivityCategory cat = ConnectivityProvider.getInstance().getCategoriesById(cdcConn.getId());
                    return DenguesTextUtil.getNotNullString(cat.getType().getDisplayName());
                case 2:
                    return DenguesTextUtil.getNotNullString(type.getSbsTable());
                }
            }
            return "";
        }

        /*
         * (non-Javadoc)
         * 
         * @see org.eclipse.jface.viewers.IStructuredContentProvider#getElements(java.lang.Object)
         */
        public Object[] getElements(Object inputElement) {
            if (inputElement instanceof List) {
                return ((List) inputElement).toArray(new Object[0]);
            }
            return new Object[0];
        }

        /*
         * (non-Javadoc)
         * 
         * @see org.eclipse.jface.viewers.IContentProvider#inputChanged(org.eclipse.jface.viewers.Viewer,
         * java.lang.Object, java.lang.Object)
         */
        public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {

        }

    }

    private TableViewer tableViewer;

    private List<CDCConnType> cdcConns;

    /**
     * Qiang.Zhang.Adolf@gmail.com CDCSettingsViewer constructor comment.
     * 
     * @param parent
     * @param style
     * @param bottons
     */
    public CDCSettingsViewer(Composite parent, int style) {
        super(parent, style, ADD_BUTTON | REMOVE_BUTTON);
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.dengues.ui.prefs.StructuredViewerAndButtons#createStructuredViewer(org.eclipse.swt.widgets.Composite)
     */
    @Override
    public StructuredViewer createStructuredViewer(Composite parent) {
        tableViewer = new TableViewer(parent, SWT.MULTI | SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION
                | SWT.VIRTUAL);
        final Table table = tableViewer.getTable();
        table.setHeaderVisible(true);
        table.setLinesVisible(true);
        CDCViewerProvider provider = new CDCViewerProvider();
        tableViewer.setContentProvider(provider);
        tableViewer.setLabelProvider(provider);
        createColumns(table);
        return tableViewer;
    }

    /**
     * Qiang.Zhang.Adolf@gmail.com Comment method "createColumns".
     */
    private void createColumns(final Table table) {
        // create listener for sorting
        Listener sortListener = new Listener() {

            public void handleEvent(Event e) {

                // determine new sort column and direction
                TableColumn sortColumn = table.getSortColumn();
                TableColumn currentColumn = (TableColumn) e.widget;
                int dir = table.getSortDirection();
                if (sortColumn == currentColumn) {
                    dir = dir == SWT.UP ? SWT.DOWN : SWT.UP;
                } else {
                    table.setSortColumn(currentColumn);
                    dir = SWT.UP;
                }

                // update data displayed in table
                table.setSortDirection(dir);
                table.clearAll();
            }
        };

        TableColumn column = new TableColumn(tableViewer.getTable(), SWT.NONE);
        column.setText("Name");
        column.setWidth(100);
        column.addListener(SWT.Selection, sortListener);
        column.setData("orignalColumnIndex", new Integer(0));
        column = new TableColumn(tableViewer.getTable(), SWT.NONE);
        column.setText("DB Type");
        column.addListener(SWT.Selection, sortListener);
        column.setData("orignalColumnIndex", new Integer(1));
        column.setWidth(100);
        // column = new TableColumn(tableViewer.getTable(), SWT.NONE);
        // column.setText("Host");
        // column.pack();
        // column = new TableColumn(tableViewer.getTable(), SWT.NONE);
        // column.setText("Instance");
        // column.pack();
        column = new TableColumn(tableViewer.getTable(), SWT.NONE);
        column.setText("SBS Table");
        column.setWidth(150);
        // column = new TableColumn(tableViewer.getTable(), SWT.NONE);
        // column.setText("Schema");
        // column.pack();
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.dengues.ui.prefs.StructuredViewerAndButtons#setInput(java.lang.Object)
     */
    @Override
    public void setInput(Object data) {
        super.setInput(data);
        cdcConns = (List<CDCConnType>) data;
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.dengues.ui.prefs.StructuredViewerAndButtons#addButtonAction(org.eclipse.jface.viewers.StructuredSelection)
     */
    @Override
    protected void addButtonAction(StructuredSelection selection) {
        ProjectType projectType = DenguesProjectFactory.getDenguesProject().getProjectType();
        List<ConnPropertySetType> usefulConns = new ArrayList<ConnPropertySetType>();
        EList<ConnPropertySetType> connProperties = projectType.getConnProperties();
        for (ConnPropertySetType cSet : connProperties) {
            if (cSet.getCdcConn() == null) {
                usefulConns.add(cSet);
            }
        }
        if (!usefulConns.isEmpty()) {
            CDCSettingDialog dialog = new CDCSettingDialog(getShell(), usefulConns.get(0));
            if (dialog.open() == CDCSettingDialog.OK) {
                setInput(projectType.getCdcConns());
                tableViewer.refresh();
                refreshWarehouseView();
            }
        } else {
            MessageDialog.openInformation(getShell(), "Connectivity", "No Connivity can be useful, Please add connectivity.");
        }
    }

    /**
     * Qiang.Zhang.Adolf@gmail.com Comment method "refreshWarehouseView".
     */
    private void refreshWarehouseView() {
        IWorkbenchWindow aww = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
        if (aww != null) {
            IWorkbenchPage ap = aww.getActivePage();
            if (ap != null) {
                IViewPart fw = ap.findView(IDenguesCoreContants.WAREHOUSE_VIEW_ID);
                if (fw instanceof IWarehouseView) {
                    IWarehouseView view = (IWarehouseView) fw;
                    view.refresh();
                }
            }
        }
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.dengues.ui.prefs.StructuredViewerAndButtons#removeButtonAction(org.eclipse.jface.viewers.StructuredSelection)
     */
    @Override
    protected void removeButtonAction(StructuredSelection selection) {
        ProjectType projectType = DenguesProjectFactory.getDenguesProject().getProjectType();
        EList<CDCConnType> cdcConns2 = projectType.getCdcConns();
        if (selection != null && selection.size() > 0) {
            List list = selection.toList();
            for (Object object : list) {
                if (object instanceof CDCConnType) {
                    CDCConnType connType = (CDCConnType) object;
                    ChangeDataCaptureManager cManager = new ChangeDataCaptureManager(connType.getConnSet());
                    ExecuteCDCSQLDialog dialog = new ExecuteCDCSQLDialog(getShell(), cManager, cManager.genDelSysSubscriberSQL(),
                            false);
                    dialog.open();
                    if (dialog.isExec()) {
                        List<Object> aobe = WarehouseResourceFactory.getAllObjectsFromEMF(ENodeCategoryName.DATABASE);
                        for (Object o2 : aobe) {
                            DatabaseDiagram diagram = (DatabaseDiagram) o2;
                            ConnPropertySetType cst = MetadataHelper.getConnSetType(diagram);
                            if (cst == connType.getConnSet()) {
                                EList<DiagramChild> dbChildren = diagram.getDbChildren();
                                for (DiagramChild dch : dbChildren) {
                                    if (dch instanceof DBTable) {
                                        DBTable table = (DBTable) dch;
                                        table.setActivateCdc(false);
                                        table.setCdcConn(null);
                                    }
                                }
                            }
                            WarehouseResourceFactory.saveStorage(diagram);
                        }
                        connType.getConnSet().setCdcConn(null);
                        cdcConns2.remove(connType);
                        refreshWarehouseView();
                    }
                }
            }
            WarehouseResourceFactory.save(projectType);
            setInput(cdcConns2);
            tableViewer.refresh();
        }
    }

    /**
     * Getter for tableViewer.
     * 
     * @return the tableViewer
     */
    public TableViewer getTableViewer() {
        return this.tableViewer;
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.dengues.ui.prefs.StructuredViewerAndButtons#updateButtons(java.lang.Object)
     */
    @Override
    protected void updateButtons(Object object) {
        super.updateButtons(object);
        if (object instanceof CDCConnType) {
            Collection<Button> values = butonsMap.values();
            for (Button button : values) {
                button.setEnabled(true);
            }
            Collection<Action> values2 = actionsMap.values();
            for (Action action : values2) {
                action.setEnabled(true);
            }
        }
    }
}
